package edu.wy.smartcaneadmin.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class WechatUtil {

    private static final Logger logger = LoggerFactory.getLogger(WechatUtil.class);

    @Value("${wechat.appid}")
    private String APPID;

    @Value("${wechat.secret}")
    private String SECRET;

    @Value("${wechat.jscode2session.url}")
    private String requestUrl;

    @Value("${wechat.grant_type}")
    private String grantType;

    public JSONObject getSessionKeyOrOpenId(String code) {
        if (code == null || code.isEmpty()) {
            logger.error("参数 'code' 为空或无效。");
            throw new IllegalArgumentException("参数 'code' 不能为空或无效。");
        }

        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", APPID);
        requestUrlParam.put("secret", SECRET);
        requestUrlParam.put("js_code", code);
        requestUrlParam.put("grant_type", grantType);

        try {
            String response = HttpClientUtil.doPost(requestUrl, requestUrlParam);
            if (response == null || response.isEmpty()) {
                logger.error("从微信API获取的响应为空或无效。");
                throw new RuntimeException("从微信API获取会话密钥或OpenID失败。");
            }
            return JSON.parseObject(response);
        } catch (Exception e) {
            logger.error("调用微信API时发生错误: {}", e.getMessage(), e);
            throw new RuntimeException("调用微信API失败。", e);
        }
    }
}
